package hms.RoomManagementModule;

import hms.UserAccountsModule.UserAccount;
import hms.database.DAO;
import hms.database.DAOnoGUI;
import hms.generic.AbstractGlobalView;
import hms.master.MasterController;
import hms.rooms.AmenitiesHandler;
import hms.rooms.Room;
import hms.rooms.RoomTable;
import hms.rooms.RoomType;
import hms.rooms.RoomTypeTable;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ConfigureRoomsView extends AbstractGlobalView implements ListSelectionListener{
	
	ConfigureRoomsPanel panel;
	EditRoomTypePanel editTypePanel;
	AmenitiesHandler amenitiesHandler;
	
	Room selectedRoom = null, newRoom = new Room();
	RoomTable rooms;
	
	boolean doNotListenToChange = false;
	
	private NewRoomTypePanel newTypePanel;
	
	public ConfigureRoomsView(){
		
		amenitiesHandler = new AmenitiesHandler();
		
		panel = new ConfigureRoomsPanel(this);
		
		rooms = new RoomTable();
		
		super.update(panel);
		super.display();
		
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// If add room button is clicked
		if(e.getActionCommand().equalsIgnoreCase("btn_addRoom")){
			clickButtonAddRoom();
		}
		
		// If updated button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_updateRoom")){
			selectedRoom = rooms.getRoomByLabel((String) panel.list_rooms.getSelectedValue());
			clickButtonUpdate();
		}
		
		// If remove button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_removeRoom")){
			clickButtonRemove();
		}
		
		// If new type button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_newType")){
			clickButtonNewType();
		}
		
		// If New Type, save button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_saveNewType")){
			try {
				clickButtonSaveNewType();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		// If Edit Type button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_editType")){
				try {
					clickButtonEditRoomType();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		}
		
		// If remove room type button is clicked
		else if(e.getActionCommand().equalsIgnoreCase("btn_remove")){
			clickedButtonRemoveRoomType();
		}
		
		// If Save is clicked on Edit Room Type panel
		else if(e.getActionCommand().equalsIgnoreCase("btn_saveUpdatedType")){
			try {
				clickButtonSaveUpdatedRoomType();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		// Click outside list of rooms
		else if(e.getActionCommand().equalsIgnoreCase("clickOutsideList")){
			panel.list_rooms.setSelectedIndex(-1);
		}
	}
	
	private void clickedButtonRemoveRoomType(){
		RoomTable roomst = new RoomTable();
		boolean okToRemove = true;
		
		DAO tempDAO = DAOnoGUI.getDAO();
		
		for(int i = 0; i < roomst.getSize(); i++){
			Room room = roomst.get(i);
			if(room.getRoomTypeLabel().equalsIgnoreCase((String)panel.combo_roomTypes.getSelectedItem())){
				JOptionPane.showMessageDialog(editTypePanel, "Room Type cannot be removed because it associated with existing rooms!",
						"Error", 
						JOptionPane.ERROR_MESSAGE);
				
				okToRemove = false;
			}
			if(!okToRemove)
				break;
		}
		
		if(okToRemove){
			Object[] options = {"Yes", "Cancel"};
			
			int response = JOptionPane.showOptionDialog(editTypePanel, 
					"Are you sure you want to permanently remove this room typeand all associated information from the database?",
					"CONFIRM PERMANENT DELETION OF ROOM TYPE INFORMATION",
					JOptionPane.OK_CANCEL_OPTION,
					JOptionPane.PLAIN_MESSAGE,
					null,
					options,
					options[0]);
			
			if(response == JOptionPane.YES_OPTION){
				tempDAO.updateCommand("DELETE FROM INCLUDES_AMENTITIES WHERE " +
						"ROOMTYPELABEL = '" + (String)panel.combo_roomTypes.getSelectedItem() + "';");
				tempDAO.updateCommand("DELETE FROM ROOM_TYPE WHERE " +
						"ROOMTYPELABEL = '" + (String)panel.combo_roomTypes.getSelectedItem() + "';");

			}
			
			panel.model.removeElement((String)panel.combo_roomTypes.getSelectedItem());
		}
		
		
		editTypePanel.dispose();
		

		
		
	}
	
	/**
	 * Handle events when saving updated type from edit room panel
	 * @throws SQLException 
	 */
	private void clickButtonSaveUpdatedRoomType() throws SQLException{
		// If number of beds is not a number or is empty
		if(!editTypePanel.txt_numBeds.getText().matches("^\\d*$") ||
			editTypePanel.txt_numBeds.getText().isEmpty()){
			JOptionPane.showMessageDialog(editTypePanel, "Number of beds must be a number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If price is not a number or is empty
		else if(!editTypePanel.txt_price.getText().matches("^\\d*$") ||
			editTypePanel.txt_price.getText().isEmpty()){
			JOptionPane.showMessageDialog(editTypePanel, "Price must be a number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If bed size is empty
		else if(editTypePanel.txt_bedSize.getText().isEmpty()){
			JOptionPane.showMessageDialog(editTypePanel, "Must include a bed size!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If everything is okay
		else{
			RoomType thisType = (new RoomTypeTable()).getRoomTypeByLabel((String)panel.combo_roomTypes.getSelectedItem());
			
			String typeLabel = "", bedSize, isSmokingAllowed, isConnectable;
			int numBeds, price;
			DAO tempDAO = DAOnoGUI.getDAO();
			
			typeLabel = (String)panel.combo_roomTypes.getSelectedItem();
			bedSize = editTypePanel.txt_bedSize.getText();
			numBeds = Integer.parseInt(editTypePanel.txt_numBeds.getText());
			price = Integer.parseInt(editTypePanel.txt_price.getText());
			
			// Get smoking allowed value
			if(editTypePanel.chk_isSmokingAllowed.isSelected())
				isSmokingAllowed = "T";
			else
				isSmokingAllowed = "F";

			
			String updateString = "UPDATE ROOM_TYPE " +
					"SET PRICEPERNIGHT=" + price +
					", BEDSIZE='" + bedSize + "'" +
					", NUMBEROFBEDS=" + numBeds +
					", ISSMOKINGALLOWED='" + isSmokingAllowed + "'" +
					", ISCONNECTABLE='F'" +
					" WHERE ROOMTYPELABEL='" + typeLabel + "';";
					
			tempDAO.updateCommand(updateString);

			// Refrigerator
			if(editTypePanel.chk_refrigerator.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Refrigerator");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Refrigerator");
			
			// Microwave
			if(editTypePanel.chk_microwave.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Microwave");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Microwave");
			
			// Couch
			if(editTypePanel.chk_couch.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Couch");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Couch");
			
			// Pull-out Cot
			if(editTypePanel.chk_pullOutCot.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Pull-out Cot");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Pull-out Cot");
			
			// Desk
			if(editTypePanel.chk_desk.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Desk");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Desk");
			
			// Free HBO
			if(editTypePanel.chk_hbo.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Free HBO");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Free HBO");
			
			// Ethernet
			if(editTypePanel.chk_ethernet.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Ethernet");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Ethernet");
			
			// Alarm Clock
			if(editTypePanel.chk_alarmClock.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Alarm Clock");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Alarm Clock");
			
			// Balcony
			if(editTypePanel.chk_balcony.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Balcony");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Balcony");
			
			// Ceiling Fan
			if(editTypePanel.chk_ceilingFan.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Ceiling Fan");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Ceiling Fan");
			
			// Floor Fan
			if(editTypePanel.chk_floorfan.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "Floor Fan");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "Floor Fan");
			
			// DVD Rentals
			if(editTypePanel.chk_dvdRentals.isSelected())
				amenitiesHandler.addAmenityToDatabase(typeLabel, "DVD Rentals");
			else
				amenitiesHandler.removeAmenityFromDatabase(typeLabel, "DVD Rentals");
			
			editTypePanel.dispose();
		}
	}
	
	/**
	 * Handle events when Edit Room Type button is clicked
	 * @throws SQLException 
	 */
	private void clickButtonEditRoomType() throws SQLException{
		
		RoomType thisType = (new RoomTypeTable()).getRoomTypeByLabel((String)panel.combo_roomTypes.getSelectedItem());
		editTypePanel = new EditRoomTypePanel(thisType, this);
		
		
		String typeLabel = thisType.getRoomTypeLabel();
		
		DAO tempDAO = DAOnoGUI.getDAO();
		
		editTypePanel.lblTypeLabel.setText("Type Label: " + typeLabel);
		editTypePanel.txt_bedSize.setText(thisType.getBedSize());
		editTypePanel.txt_numBeds.setText("" + thisType.getNumberOfBeds());
		editTypePanel.txt_price.setText("" + thisType.getPricePerNight());
		
		if(thisType.getSmokingAllowed() == 'T')
			editTypePanel.chk_isSmokingAllowed.setSelected(true);
		
		// Refrigerator
		if(amenitiesHandler.exists(typeLabel, "Refrigerator"))
			editTypePanel.chk_refrigerator.setSelected(true);
		else
			editTypePanel.chk_refrigerator.setSelected(false);
		
		// Microwave
		if(amenitiesHandler.exists(typeLabel, "Microwave"))
			editTypePanel.chk_microwave.setSelected(true);
		else
			editTypePanel.chk_microwave.setSelected(false);
		
		// Couch
		if(amenitiesHandler.exists(typeLabel, "Couch"))
			editTypePanel.chk_couch.setSelected(true);
		else
			editTypePanel.chk_couch.setSelected(false);
		
		// Pull-out Cot
		if(amenitiesHandler.exists(typeLabel, "Pull-out Cot"))
			editTypePanel.chk_pullOutCot.setSelected(true);
		else
			editTypePanel.chk_pullOutCot.setSelected(false);
		
		// Desk
		if(amenitiesHandler.exists(typeLabel, "Desk"))
			editTypePanel.chk_desk.setSelected(true);
		else
			editTypePanel.chk_desk.setSelected(false);
		
		// Free HBO
		if(amenitiesHandler.exists(typeLabel, "Free HBO"))
			editTypePanel.chk_hbo.setSelected(true);
		else
			editTypePanel.chk_hbo.setSelected(false);
		
		// Ethernet
		if(amenitiesHandler.exists(typeLabel, "Ethernet"))
			editTypePanel.chk_ethernet.setSelected(true);
		else
			editTypePanel.chk_ethernet.setSelected(false);
		
		// Alarm Clock
		if(amenitiesHandler.exists(typeLabel, "Alarm Clock"))
			editTypePanel.chk_alarmClock.setSelected(true);
		else
			editTypePanel.chk_alarmClock.setSelected(false);
		
		// Balcony
		if(amenitiesHandler.exists(typeLabel, "Balcony"))
			editTypePanel.chk_balcony.setSelected(true);
		else
			editTypePanel.chk_balcony.setSelected(false);
		
		// Ceiling Fan
		if(amenitiesHandler.exists(typeLabel, "Ceiling Fan"))
			editTypePanel.chk_ceilingFan.setSelected(true);
		else
			editTypePanel.chk_ceilingFan.setSelected(false);
		
		// Floor Fan
		if(amenitiesHandler.exists(typeLabel, "Floor Fan"))
			editTypePanel.chk_floorfan.setSelected(true);
		else
			editTypePanel.chk_floorfan.setSelected(false);
		
		// DVD Rentals
		if(amenitiesHandler.exists(typeLabel, "DVD Rentals"))
			editTypePanel.chk_dvdRentals.setSelected(true);
		else
			editTypePanel.chk_dvdRentals.setSelected(false);

		editTypePanel.setVisible(true);
				
	}
	
	/**
	 * Validate that new room type entered is acceptable
	 */
	private boolean newRoomTypeLabelIsValidated(){
		
		for(int i = 0; i < panel.combo_roomTypes.getItemCount(); i++){
			if( panel.combo_roomTypes.getItemAt(i).toString().equalsIgnoreCase(newTypePanel.txt_roomTypeLabel.getText()))
				return false;
		}

		if(newTypePanel.txt_roomTypeLabel.getText().matches("^[ \\t]*$"))
			return false;
		
		if(newTypePanel.txt_roomTypeLabel.getText().isEmpty())
			return false;
		
		else
			return true;
	}
	
	/**
	 * Handle events when a New Type is saved
	 * @throws SQLException 
	 */
	private void clickButtonSaveNewType() throws SQLException{
		
		String roomTypeLabel = "", bedSize, isSmokingAllowed, isConnectable;
		int numBeds, price;
		DAO tempDAO;
		// If number of beds is not a number or is empty
		if(!newTypePanel.txt_numBeds.getText().matches("^\\d*$") ||
			newTypePanel.txt_numBeds.getText().isEmpty()){
			JOptionPane.showMessageDialog(newTypePanel, "Number of beds must be a number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If price is not a number or is empty
		else if(!newTypePanel.txt_price.getText().matches("^[\\d.]*$") ||
			newTypePanel.txt_price.getText().isEmpty()){
			JOptionPane.showMessageDialog(newTypePanel, "Price must be a number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If room type label is invalid
		else if(!newRoomTypeLabelIsValidated()){
			JOptionPane.showMessageDialog(newTypePanel, "Invalid Room Type! Cannot be duplicate or empty!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If bed size is empty
		else if(newTypePanel.txt_bedSize.getText().isEmpty()){
			JOptionPane.showMessageDialog(newTypePanel, "Must include a valid bed size!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		// If everything is okay
		else{
			
			// Get values for basic info
			roomTypeLabel = newTypePanel.txt_roomTypeLabel.getText();
			bedSize = newTypePanel.txt_bedSize.getText();
			numBeds = Integer.parseInt(newTypePanel.txt_numBeds.getText());
			price = (int) Math.round(Double.parseDouble(newTypePanel.txt_price.getText()));
			
			// Get smoking allowed value
			if(newTypePanel.chk_isSmokingAllowed.isSelected())
				isSmokingAllowed = "T";
			else
				isSmokingAllowed = "F";
		
			tempDAO = DAOnoGUI.getDAO();
			
			tempDAO.updateCommand("INSERT INTO ROOM_TYPE (ROOMTYPELABEL, PRICEPERNIGHT," +
					" ISSMOKINGALLOWED, ISCONNECTABLE, BEDSIZE, NUMBEROFBEDS) VALUES('" +
					roomTypeLabel + "', " + price + ", '" + isSmokingAllowed + "', 'F', '" + bedSize + "', " + numBeds + ");");
			
			// UPDATE ALL AMENITIES //
			
			// Refrigerator
			if(newTypePanel.chk_refrigerator.isSelected())
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Refrigerator");
			
			// Microwave
			if(newTypePanel.chk_microwave.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Microwave");
			}
			// Refrigerator
			if(newTypePanel.chk_couch.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Couch");
			}
			// Refrigerator
			if(newTypePanel.chk_pullOutCot.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Pull-out Cot");
			}
			// Refrigerator
			if(newTypePanel.chk_desk.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Desk");
			}
			// Refrigerator
			if(newTypePanel.chk_ethernet.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Free HBO");
			}
			// Refrigerator
			if(newTypePanel.chk_hbo.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Ethernet");
			}
			// Refrigerator
			if(newTypePanel.chk_alarmClock.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Alarm Clock");
			}
			// Refrigerator
			if(newTypePanel.chk_balcony.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Balcony");
			}
			// Refrigerator
			if(newTypePanel.chk_ceilingFan.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Ceiling Fan");
			}
			// Refrigerator
			if(newTypePanel.chk_floorfan.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "Floor Fan");
			}
			// Refrigerator
			if(newTypePanel.chk_dvdRentals.isSelected()){
				amenitiesHandler.addAmenityToDatabase(roomTypeLabel, "DVD Rentals");
			}
			
			newTypePanel.dispose();
			panel.model.addElement(roomTypeLabel);
		}
		rooms.reloadFromDatabase();
		//rooms.fillFromDatabase();
		//panel.model.addElement(roomTypeLabel);

	}
	
	/**
	 * Handle events when New Type button is clicked
	 */
	private void clickButtonNewType(){
		newTypePanel = new NewRoomTypePanel((new RoomTypeTable()).getRoomTypeByLabel( (String)panel.combo_roomTypes.getSelectedItem()), this);
		newTypePanel.setVisible(true);	
	}
	
	/**
	 * Handle events when Remove button is clicked
	 */
	public void clickButtonRemove(){
		Object[] options = {"Yes", "Cancel"};
		
		int response = JOptionPane.showOptionDialog(panel, 
				"Are you sure you want to permanently remove this room and all associated information from the database?",
				"CONFIRM PERMANENT DELETION OF ROOM INFORMATION",
				JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.PLAIN_MESSAGE,
				null,
				options,
				options[0]);
		
		String panelToRemove = panel.txt_label.getText();
		if(response == JOptionPane.YES_OPTION){
			DAO tempDAO = DAOnoGUI.getDAO();
			tempDAO.updateCommand("DELETE FROM ROOM WHERE " +
					"ROOMLABEL = '" + panelToRemove + "';");
		}
		panel.list_rooms.setSelectedIndex(0);
		panel.listModel.removeElement(panelToRemove);
		
	}
	
	/**
	 * Handle events when Update button is clicked
	 */
	public void clickButtonUpdate(){
		
		
		// If room label does NOT exist AND floor is only a number
		if(rooms.getRoomByLabel(panel.txt_label.getText()) == null && floorIsOnlyNumbers() && !panel.txt_label.getText().isEmpty()){
			updateRoomInformation();
		}
		
		// If room label is the same as the selected room
		else if(rooms.getRoomByLabel(panel.txt_label.getText()).equals(selectedRoom)
				&& floorIsOnlyNumbers() && !panel.txt_label.getText().isEmpty()){
			updateRoomInformation();
		}
		
		// If floor contains things other than numbers
		else if(!floorIsOnlyNumbers()){
			JOptionPane.showMessageDialog(panel, "You can only input numbers with no spaces for the floor number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		
		// If label is blank
		else if(panel.txt_label.getText().isEmpty()){
			JOptionPane.showMessageDialog(panel, "Label text cannot be blank!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		
		// If room label already exists in database
		else if(rooms.getRoomByLabel(panel.txt_label.getText()) != null){
			JOptionPane.showMessageDialog(panel, "This room already exists in the database!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Update room information
	 */
	private void updateRoomInformation(){
		
		selectedRoom.setAdditionalNotes(panel.txt_additionalNotes.getText());
		selectedRoom.setRoomLabel(panel.txt_label.getText());
		selectedRoom.setRoomTypeLabel((String)panel.combo_roomTypes.getSelectedItem());
		selectedRoom.setFloorNumber(Integer.parseInt(panel.txt_floor.getText()));
		selectedRoom.commitToDatabase();
		
		panel.listModel.clear();
		panel.listModel.ensureCapacity(rooms.size() + 1);
		panel.listModel.addElement("-- Add New Room --");
		for(Room rr : rooms) {
			if(!rr.isMarkedForDeletion())
			panel.listModel.addElement(rr.getRoomLabel());
		}

		panel.list_rooms.setModel(panel.listModel);
		panel.list_rooms.setSelectedIndex(-1);
		panel.list_rooms.validate();
		
		
	}
	
	/**
	 * Check to see if label passed in to this method is a unique room label or not.
	 * Return true if it is, return false if it is not
	 */
	private boolean isRoomLabelUnique(String label){
		
		//rooms.fillFromDatabase();
		
		if(rooms.getRoomByLabel(label) == null)
			return true;
		else
			return false;
	}
	

	/**
	 * Handle events when Add Room button is clicked
	 */
	public void clickButtonAddRoom(){
		
		//RoomTable rooms = new RoomTable();
		
		// If room label does not already exist AND floor is only a number
		if(rooms.getRoomByLabel(panel.txt_label.getText()) == null && floorIsOnlyNumbers() && !panel.txt_label.getText().isEmpty()
				&& isRoomLabelUnique(panel.txt_label.getText())){
			Object[] options = {"Yes", "Cancel"};
			
			int response = JOptionPane.showOptionDialog(panel, 
					"Are you sure you want to add this room to the database?",
					"Confirm Room Addition",
					JOptionPane.OK_CANCEL_OPTION,
					JOptionPane.PLAIN_MESSAGE,
					null,
					options,
					options[0]);
			
			if(response == JOptionPane.YES_OPTION){
				
				// for some reason, caught in infinite loop when committing to database
				String insertRoomSQL = "INSERT INTO ROOM(ROOMLABEL, ROOMTYPELABEL, FLOOR, ADDITIONALNOTES, OCCUPATIONSTATUS) " +
						"VALUES(?,?,?,?,?)";
				
				String rmLbl ="";
				String rmTypeLbl ="";
				String addtlNotes ="";
				int rmFlrNumber = -1;
				String ocupStatus = "Empty";
				
				rmLbl =panel.txt_label.getText();
				rmTypeLbl =(String)panel.combo_roomTypes.getSelectedItem();
				
				if(panel.txt_additionalNotes.getText() != null &&
						!panel.txt_additionalNotes.getText().trim().isEmpty() &&
						panel.txt_additionalNotes.getText().length()<1000){
					addtlNotes = panel.txt_additionalNotes.getText();
				}
				rmFlrNumber = Integer.parseInt(panel.txt_floor.getText());
				DAO db = DAOnoGUI.getDAO();
				PreparedStatement roomPS = db.generatePreparedStatement(insertRoomSQL);

				//System.out.println(roomPS);
				try {
					// manually insert room
					roomPS.setString(1,rmLbl);
					roomPS.setString(2,rmTypeLbl);
					roomPS.setInt(3, rmFlrNumber);
					roomPS.setString(4,addtlNotes);
					roomPS.setString(5, ocupStatus);
					db.executePreparedUpdate(roomPS);
					//roomPS.execute();

					//System.out.println(roomPS);
					
				} catch (SQLException e) {
				//	System.out.println(roomPS);
					e.printStackTrace();
					
					JOptionPane.showMessageDialog(null, "Error with inserting room data.  Please ensure room label is unique!",
							"Error", 
							JOptionPane.ERROR_MESSAGE);
				}
				// reload from database after manual room insert
				rooms.reloadFromDatabase();
				
	/**
				if(selectedRoom==null){
					selectedRoom = new Room();
				}
				selectedRoom.setAdditionalNotes(panel.txt_additionalNotes.getText());
				selectedRoom.setRoomLabel(panel.txt_label.getText());
				selectedRoom.setRoomTypeLabel((String)panel.combo_roomTypes.getSelectedItem());
				selectedRoom.setFloorNumber(Integer.parseInt(panel.txt_floor.getText()));
				selectedRoom.commitToDatabase();
				**/
				panel.listModel.clear();
				panel.listModel.ensureCapacity(rooms.size() + 1);
				panel.listModel.addElement("-- Add New Room --");
				for(Room rr : rooms) {
					if(!rr.isMarkedForDeletion())
					panel.listModel.addElement(rr.getRoomLabel());
				}

				panel.list_rooms.setModel(panel.listModel);
				panel.list_rooms.setSelectedIndex(-1);
				panel.list_rooms.validate();
				
			}
		}
		
		// If floor contains things other than numbers
		else if(!floorIsOnlyNumbers()){
			JOptionPane.showMessageDialog(null, "You can only input numbers with no spaces for the floor number!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		
		// If label is blank
		else if(panel.txt_label.getText().isEmpty()){
			JOptionPane.showMessageDialog(null, "Label text cannot be blank!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
		
		// If room label already exists in database
		else if(!isRoomLabelUnique(panel.txt_label.getText())){
			JOptionPane.showMessageDialog(null, "This room already exists in the database!",
					"Error", 
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Returns true if the floor field has only numbers, false otherwise
	 */
	private boolean floorIsOnlyNumbers(){
		if(!panel.txt_floor.getText().matches("^\\d*$") || panel.txt_floor.getText().isEmpty())
			return false;
		else
			return true;
	}
	
	/**
	 * When an item is clicked on in the JList of rooms
	 */
	@Override
	public void valueChanged(ListSelectionEvent e) {
		
		if(e.getValueIsAdjusting() == false){
			panel.enableUpdateButton();
			if(panel.list_rooms.getSelectedIndex() == -1 || panel.list_rooms.getSelectedIndex() == 0){
				panel.disableUpdateButton();
				panel.disableRemoveButton();
				panel.enableAddRoomButton();
				panel.lbl_occupiedStatus.setText("");
				panel.txt_additionalNotes.setText("");
				panel.txt_floor.setText("");
				panel.txt_label.setText("");
				panel.combo_roomTypes.setSelectedIndex(0);
				selectedRoom = new Room();
			}
			else{
				updateSelectedRoom();
				fillInFields();
				
				panel.disableAddRoomButton();
				
				panel.enableUpdateButton();
				if(selectedRoom.getOccupationStatus().equalsIgnoreCase("empty")){
					panel.enableRemoveButton();
					panel.lbl_occupiedStatus.setForeground(Color.BLACK);
					panel.lbl_occupiedStatus.setText("");
				}
				else{
					panel.disableRemoveButton();
					
					panel.lbl_occupiedStatus.setForeground(Color.RED);
					panel.lbl_occupiedStatus.setText(selectedRoom.getOccupationStatus());
					
				}
			}
			
		}
	}
	
	/**
	 * Assign the chosen room to the selectedRoom object
	 */
	private void updateSelectedRoom(){
		String selectedRoomLabel = (String) panel.list_rooms.getSelectedValue();
		selectedRoom = rooms.getRoomByLabel(selectedRoomLabel);
	}
	
	/**
	 * Fill in all the fields with the information from the currently selected room
	 */
	private void fillInFields(){
	
		if(selectedRoom == null)
			selectedRoom = rooms.getRoomByLabel((String)panel.list_rooms.getSelectedValue());
		if(selectedRoom != null){
			panel.txt_floor.setText("" + selectedRoom.getFloorNumber());
			
			panel.txt_label.setText(selectedRoom.getRoomLabel());
			
			panel.txt_additionalNotes.setText(selectedRoom.getAdditionalNotes());
			
			panel.combo_roomTypes.setSelectedItem(selectedRoom.getRoomTypeLabel());
		}

	}

}
